<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="1.5">
        <el-input size="mini" placeholder="输入关键字进行过滤" />
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['datamodel']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['datamodel']"
          >导出</el-button
        >
      </el-col>
    </el-row>
    <el-row>
      <el-table
        style="margin-top: 10px"
        v-loading="loading"
        :data="defineList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="标识" align="left" prop="code">
          <template slot-scope="scope">
            <router-link
              :to="'/lc/datamodel/define-columns/index/' + scope.row.id"
              class="link-type"
            >
              <span>{{ scope.row.code }}</span>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column label="标题" align="left" prop="title" />
        <el-table-column label="所属分组" align="center" prop="groupTitle" />
        <el-table-column label="类型" align="center" prop="type">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.lc_datamodel_type"
              :value="scope.row.type"
            />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="state">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.lc_datamodel_state"
              :value="scope.row.state"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              :disabled="scope.row.state == 1"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['datamodel']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['datamodel']"
              >删除</el-button
            >
            <el-button
              :disabled="scope.row.state == 1"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handlePublish(scope.row)"
              v-hasPermi="['datamodel']"
              >发布</el-button
            >
            <el-button
              :disabled="scope.row.state != 1"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleWeihu(scope.row)"
              v-hasPermi="['datamodel']"
              >维护</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-row>

    <!-- 添加或修改数据建模对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属分组" prop="groupCode">
          <treeselect
            v-model="form.groupCode"
            :options="groupOptions"
            :normalizer="normalizer"
            placeholder="选择所属分组"
          />
        </el-form-item>
        <el-form-item label="标识" prop="code">
          <el-input
            v-model="form.code"
            placeholder="请输入标识"
            :disabled="this.form.id != null"
          />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" clearable>
            <el-option
              v-for="item in dict.type.lc_datamodel_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="确认删除定义"
      :visible.sync="delOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="delForm"
        :model="delForm"
        :rules="delRules"
        label-width="80px"
      >
        <el-form-item label="ID" prop="id" v-show="false">
          <el-input v-model="delForm.id" />
        </el-form-item>
        <el-form-item label="标识" prop="code">
          <el-input v-model="delForm.code" placeholder="请输入标识" disabled />
        </el-form-item>
        <el-form-item label="输入标识" prop="delCode">
          <el-input
            v-model="delForm.delCode"
            placeholder="请输入要删除的定义标识"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="submitDel">删除</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  listDefine,
  getDefine,
  delDefine,
  addDefine,
  updateDefine,
  publishDefine,
  weihuDefine,
} from "@/api/lc/lcDatamodelDefine";

import { listGroup } from "@/api/lc/lcDatamodelGroup";

export default {
  name: "Define",
  dicts: ["lc_datamodel_state", "lc_datamodel_type"],
  props: {
    selectedGroup: Object,
  },
  components: {
    Treeselect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据建模表格数据
      defineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //删除定义确认框
      delOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        title: null,
        groupCode: null,
        state: null,
        type: null,
        orderNum: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      },
      // 表单参数
      delForm: {},
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: "请输入标识", trigger: "blur" },
          {
            min: 3,
            max: 100,
            message: "长度在 3 到 100 个字符",
            trigger: "blur",
          },
        ],
        title: [
          { required: true, message: "请输入名称", trigger: "change" },
          {
            min: 3,
            max: 100,
            message: "长度在 3 到 100 个字符",
            trigger: "blur",
          },
        ],
        groupCode: [
          { required: true, message: "请选择所属分组", trigger: "change" },
        ],
        type: [{ required: true, message: "请选择类型", trigger: "blur" }],
      },
      delRules: {
        code: [{ required: true, message: "请输入标识", trigger: "blur" }],
        delCode: [
          {
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("请输入要删除的定义标识"));
              } else if (value !== this.delForm.code) {
                callback(new Error("输入的定义和原定义标识不一致!"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      groupOptions: [],
    };
  },
  watch: {
    selectedGroup() {
      this.queryParams.groupCode = this.selectedGroup.code;
      this.getList();
    },
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询数据建模列表 */
    getList() {
      this.loading = true;
      listDefine(this.queryParams).then((response) => {
        this.defineList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    cancelDel() {
      this.delOpen = false;
      this.resetDel();
    },
    resetDel() {
      this.delForm = {
        id: null,
        code: null,
        delCode: null,
      };
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        title: null,
        groupCode: null,
        state: null,
        type: null,
        orderNum: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      if (this.selectedGroup && this.selectedGroup != null) {
        this.form.groupCode = this.selectedGroup.code;
      }
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据建模";
      listGroup().then((response) => {
        this.groupOptions = this.handleTree(
          response.data,
          "code",
          "parentCode"
        );
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      let id = null;
      if (row && row.id) {
        id = row.id;
      } else {
        if (this.ids.length > 0) {
          id = this.ids[0];
        }
      }
      getDefine(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改数据建模";
        listGroup().then((response) => {
          this.groupOptions = this.handleTree(
            response.data,
            "code",
            "parentCode"
          );
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateDefine(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDefine(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitDel() {
      delDefine(this.delForm.id)
        .then(() => {
          this.delOpen = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.resetDel();
      getDefine(id).then((response) => {
        var define = response.data;
        if (define.state == "1") {
          //如果是发布中，则需要弹出确认框，输入定义编号
          this.delForm.id = define.id;
          this.delForm.code = define.code;
          this.delOpen = true;
        } else {
          this.$modal
            .confirm("确定删除？")
            .then(function () {
              return delDefine(id);
            })
            .then(() => {
              this.getList();
              this.$modal.msgSuccess("删除成功");
            })
            .catch(() => {});
        }
      });
    },

    /** 发布按钮操作 */
    handlePublish(row) {
      const ids = row.id;
      this.$modal
        .confirm('是否确认发布"' + row.code + '"？')
        .then(function () {
          return publishDefine(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("发布成功");
        })
        .catch(() => {});
    },

    /** 维护按钮操作 */
    handleWeihu(row) {
      const ids = row.id;
      weihuDefine(ids).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "datamodel/define/export",
        {
          ...this.queryParams,
        },
        `define_${new Date().getTime()}.xlsx`
      );
    },

    /** 转换options数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.code,
        code: node.code,
        label: node.title,
        children: node.children,
      };
    },
  },
};
</script>
